package ScreenWatcher

import (
	"bytes"
	"image"
	"image/png"
	"os"
	"sync"
	"time"

	"github.com/kbinani/screenshot"
	"github.com/robfig/cron/v3"
)

var (
	image_buffer *bytes.Buffer
	lock         sync.Mutex
	CaptureTime  time.Time
)

func Init() {
	image_buffer = new(bytes.Buffer)
	c := cron.New(cron.WithSeconds())
	c.AddFunc("@every 1s", Capture)
	c.Start()
}

func GetImage() string {
	lock.Lock()
	defer lock.Unlock()
	return image_buffer.String()
}

func Capture() {
	bounds := screenshot.GetDisplayBounds(0)
	img, err := screenshot.CaptureRect(bounds)
	if err != nil {
		panic(err)
	}
	lock.Lock()
	defer lock.Unlock()
	image_buffer.Reset()
	CaptureTime = time.Now()
	png.Encode(image_buffer, img)

}

// save *image.RGBA to filePath with PNG format.
func Save(img *image.RGBA, filePath string) {
	file, err := os.Create(filePath)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	png.Encode(file, img)
}
